import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import config from '../config.js';
import { getReactComponentsFromCWD } from '../utils/getReactComponentsFromCWD.js';
const app = express();

const isDev = process.env.NODE_ENV === 'development';

if (isDev) {
  console.log('当前运行模式：开发模式');
} else {
  console.log('当前运行模式：生产模式');
}

export const startServer = (config) => {
  const port = config.backendServer.port;
  app.get('/api/hello', (req, res) => {
    console.log(`收到请求：${req.url}`);
    res.send('Hello World from backend!');
  });

  app.get('/api/components', async (req, res) => {
    try {
      const components = await getReactComponentsFromCWD();
      res.json(components);
    } catch (error) {
      res.status(500).json({ error: error.message });
    }
  });

  if (!isDev) {
    const __filename = fileURLToPath(import.meta.url);
    const __dirname = dirname(__filename);
    app.use(express.static(path.join(__dirname, '../dist')));
  }

  app.listen(port, () => {
    console.log(`Backend server running at http://localhost:${port}`);
  });
};

if (isDev) {
  startServer(config);
}